extends Area2D
enum TileState  {A,
B,
C,
D,
E}

@onready var area_2d: Area2D = $Area2D

const TILE_SIZE=64

var current_state=TileState.A
var is_hovered=false #鼠标悬停
var player_in_range=false
var is_player_in_range=false

@onready var sprite_2d: Sprite2D = $Sprite2D

func _ready() -> void:
	update_texture()
	mouse_entered.connect(_on_mouse_entered)
	mouse_exited.connect(_on_mouse_exited)
	area_entered.connect(_on_area_entered)
	area_exited.connect(_on_area_exited)
	
	
func update_texture():
	var region=Rect2(current_state*TILE_SIZE,0,TILE_SIZE,TILE_SIZE)
	sprite_2d.region_rect=region
	sprite_2d.region_enabled=true
	
func _on_mouse_entered():
	is_hovered=true
	if current_state==TileState.C:
		current_state=TileState.D
	elif current_state==TileState.A and is_player_in_range==true:
		current_state=TileState.E
	elif current_state==TileState.A:
		current_state=TileState.B
		
	update_texture()
	
func _on_mouse_exited():
	is_hovered=false
	if current_state==TileState.D:
		current_state=TileState.C
	elif current_state==TileState.B or current_state==TileState.E:
		current_state=TileState.A
	update_texture()
	
@warning_ignore("unused_parameter")
func _input_event(viewport,event,shape_idx):
	if event is InputEventMouseButton and event.pressed:
		if event.button_index==MOUSE_BUTTON_LEFT:
			if current_state==TileState.E:
				queue_free()
		elif event.button_index==MOUSE_BUTTON_RIGHT:
			if (current_state==TileState.C or current_state==TileState.D) and is_player_in_range==false:
				current_state=TileState.A
			elif (current_state==TileState.C or current_state==TileState.D) and is_player_in_range==true:
				current_state=TileState.E
			elif current_state==TileState.E:
				current_state=TileState.C
			else:
				current_state=TileState.C
			if is_hovered:
				current_state=TileState.D if current_state==TileState.C else TileState.B
			update_texture()
			
func _on_area_entered(area:Area2D):
	if area.is_in_group("player"):
		is_player_in_range=true
func _on_area_exited(area:Area2D):
	if area.is_in_group("player"):
		is_player_in_range=false
			
